import React, { useState, useEffect } from 'react';

import {
    Form,
    Input,
    Button,
    Checkbox,
    Row,
    Col,
    Upload,
    Cascader,
    Select,
    Radio,
    DatePicker,
    Tabs,
    TimePicker,
    Table,
    message,
    Modal
} from 'antd';
import { LoadingOutlined, PlusOutlined, CloseCircleOutlined, UploadOutlined } from '@ant-design/icons';

import '@src/style/imgManager.scss';
import axios from "@src/lib/axios";

import cover from '@src/imgs/cover.png'

function ImgManager({ hotel_id }) {
    const [ visible, setVisible ] = useState(false);
    const [ fileList, setFileList ] = useState([]);
    const [ uploadFileList, setUploadFileList ] = useState([]);
    const [ loading, setLoading ] = useState(false);
    const files = [];

    let handleOk = () => {
        for (let i = 0; i < uploadFileList.length; i++) {
            const res = uploadFileList[i].response;
            if (res && res.code === 200) {
                console.log(uploadFileList[i])
                let { imgid, path, full_path } = res.data;
                files.push({ imgid, path, full_path, hotel_id });
            }
        }
        if (!files.length) {
            message.error('请添加图片！');
            return;
        }
        setLoading(true);
        axios.post('/product/hotel/save_img', files).then(res => {
            setLoading(false);
            if (res.code === 0) {
                getImgList();
                message.success('图片保存成功！');
                setVisible(false);
            }
        }).catch(e => setLoading(false))
    };

    let getImgList = () => {
        axios.post('/product/hotel/image_manage', { hotel_id }).then(res => {
            if (res.code === 0) {
                setFileList(res.data);
            }
        })
    };

    let setCover = (h_images_id, is_cover) => {
        axios.post('/product/hotel/set_cover', { h_images_id, is_cover }).then(res => {
            if (res.code === 0) {
                getImgList();
            }
        })
    };

    let del = (h_images_id) => {
        axios.post('/product/hotel/del_img', { h_images_id }).then(res => {
            if (res.code === 0) {
                getImgList();
                message.success('删除成功！');
            }
        })
    };

    useEffect(() => {
        getImgList();
    }, [ hotel_id ])

    let handleCancel = () => {
        setVisible(false);
    };

    function beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    }

    let imgHandleChange = (info) => {
        console.log('up===')
        let fileList = [...info.fileList];
        console.log(fileList)
        setUploadFileList([ ...fileList ]);
    }

    const props = {
        action: `${process.env.IMG_SERVER_URL}`+'/images_serv/',
        listType: 'picture',
        onChange: imgHandleChange,
        multiple: true,
        name: 'userfile',
        beforeUpload: beforeUpload,
        fileList: uploadFileList
    };

    let Footer = (
        <Row>
            <Col span={24}>
                <Button type="primary" onClick={handleOk} loading={loading}>保存</Button>
                <Button onClick={handleCancel}>取消</Button>
            </Col>
        </Row>
    );

    return (
        <div className="container">
            <Row gutter={10} className="fields-box">
                <Col span={24} style={{marginBottom: '20px'}}>
                    <Button type="primary" style={{ marginRight: '20px'}} onClick={() => {setUploadFileList([]);setVisible(true)}}>
                        <PlusOutlined/>添加图片
                    </Button>
                    {/*<Button danger>全部删除</Button>*/}
                </Col>
                {
                    fileList.map((item, index) => (

                        <Col span={3} key={index}>
                            <div className="img-box">
                                <img src={`${process.env.IMG_SERVER_URL}`+'/images_serv/' + item.imgid} alt=""/>
                                {
                                    item.is_cover === 1?
                                        <img src={cover} className="cover-img"/> : null
                                }
                                <p className="img-name" >{item.hotel_images_id}</p>
                                <div className="opera">
                                    {
                                        item.is_cover === 2?
                                            <Button type="link" onClick={() => setCover(item.h_images_id, 1)}>设为封面</Button> :
                                            <Button type="link" onClick={() => setCover(item.h_images_id, 2)}>取消封面</Button>
                                    }
                                    <Button type="link" onClick={() => del(item.h_images_id)}>删除</Button>
                                </div>
                            </div>
                        </Col>
                    ))
                }
            </Row>
            <Modal
                title="图片上传"
                visible={visible}
                maskClosable={false}
                width={'60%'}
                footer={Footer}
                onCancel={handleCancel}
            >
                <Upload {...props}>
                    <Button>
                        <UploadOutlined /> Upload
                    </Button>
                </Upload>
            </Modal>
        </div>
    )
}


export default React.memo(ImgManager);